package com.shinechain.botModel;

import com.shinechain.model.*;
import com.shinechain.utils.EndGuessThread;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import org.telegram.telegrambots.api.methods.send.SendPhoto;
import org.telegram.telegrambots.api.objects.Update;
import org.telegram.telegrambots.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.bots.DefaultBotOptions;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.exceptions.TelegramApiException;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class InviteCheckBot extends TelegramLongPollingBot {
    private long chatId = -1001389649632L;

    Update update = new Update();

    @Override
    public void onUpdateReceived(Update update) {
        this.update = update;
          /*  if (update.hasMessage() && !update.getMessage().getNewChatMembers().isEmpty()) {

                String msg = "我发现这个人:"+update.getMessage().getFrom().getUserName()+"拉了";
                for(int i =0 ; i<update.getMessage().getNewChatMembers().size() ; i++){
                    msg+= update.getMessage().getNewChatMembers().get(i).getUserName();
                }
                msg += "进群。";
                SendMessage message = new SendMessage()
                        .setChatId(update.getMessage().getChatId())
                        .setText(msg);
                try {
                    execute(message); // Call method to send the message
                } catch (TelegramApiException e) {
                    e.printStackTrace();
                }
            }*/
        if (update.hasCallbackQuery()) {
            System.out.println(update.getCallbackQuery().getData());
            hasGuessing();

        }
        if (update.hasMessage() && update.getMessage().hasText()) {
            System.out.println(update.getMessage().getText());
            if (update.getMessage().getText().equals("发竞猜")) {
                String anwser[] = {"a", "b", "c", "d"};
                this.openGussing(new File("C:\\Users\\admin\\Pictures\\hehe.jpg"), "猜一猜2018年8月24日20：00【EOS】的整数尾号", 40.0, 2.0, anwser, new Date(new Date().getTime()+6*100000));

            }
        }
        if(update.getMessage().getText().equals("结算")){
            System.out.println(this.closeGuessing(1,"b",new File("C:\\Users\\admin\\Pictures\\hehe.jpg")));

        }


    }

    //发信息、发按钮
    public boolean openGussing(File photo, String question, double tokenTotal, double tokenTimes, String answer[], Date endTime) {

        String answerCountToString = "";
        for (int i = 0; i < answer.length; i++) {
            answerCountToString += answer[i];
            answerCountToString += "**";
        }
        answerCountToString = answerCountToString.substring(0, answerCountToString.length() - 2);

        //存储到数据库
        Guess guess = new Guess();
        int guessId = WorkBot.guessMapper.selectNum() + 1;
        guess.setId(guessId);
        guess.setAnswer(answerCountToString);
        guess.setEndtime(endTime);
        String openMsg = question+"\n"+"本次官方注入"+tokenTotal+WorkBot.bitName+",单注"+tokenTimes+WorkBot.bitName+"\n"+"查询命令: /guess_"+guessId;
        guess.setQuestion(question);
        guess.setStarttime(new Date());
        guess.setTokentimes(tokenTimes);
        guess.setTokentotal(tokenTotal);

        WorkBot.guessMapper.insert(guess);

        BotMethodSwitch.guessId.add(guessId);

        SendPhoto sendPhoto = new SendPhoto();
        sendPhoto.setNewPhoto(photo);
        sendPhoto.setCaption(openMsg);
        sendPhoto.setChatId(chatId);
        InlineKeyboardMarkup replyKeyboardMarkup = new InlineKeyboardMarkup();
        List<List<InlineKeyboardButton>> rows = new ArrayList<>();
        List<InlineKeyboardButton> row = new ArrayList<>();
        String answerCount[] = {"", "一注", "十注", "梭哈"};
        String callBack[] = {"1", "2", "3"};
        for (int i = 0; i < answer.length; i++) {
            row = new ArrayList<>();
            InlineKeyboardButton button = new InlineKeyboardButton();
            button.setText(answer[i]);
            button.setCallbackData(guessId + "**" + answer[i] + "**" + 0);
            row.add(button);
            for (int j = 1; j < 4; j++) {
                InlineKeyboardButton button1 = new InlineKeyboardButton();
                button1.setText(answerCount[j]);
                System.out.println(answerCount[j]);
                button1.setCallbackData(guessId + "**" + answer[i] + "**" + callBack[j - 1]);
                row.add(button1);
            }
            rows.add(row);
        }
        replyKeyboardMarkup.setKeyboard(rows);
        sendPhoto.setReplyMarkup(replyKeyboardMarkup);
        System.out.println(replyKeyboardMarkup.toString());
        try {
            this.sendPhoto(sendPhoto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //到时间移除guessId
        EndGuessThread endGuessThread = new EndGuessThread(guessId, endTime);
        endGuessThread.start();
        return true;
    }

    //到时间，结束竞猜


    //管理员选择竞猜结果并结算
    public boolean closeGuessing(int guessId, String answerChose,File photo) {
        if(BotMethodSwitch.guessId.contains(guessId)){
            BotMethodSwitch.guessId.remove(new Integer(guessId));
        }
        Guess guess = WorkBot.guessMapper.selectByPrimaryKey(guessId);
        String answer[] = guess.getAnswer().split("\\*\\*");
        System.out.println(answerChose+"---");
        for (int i = 0; i < answer.length; i++) {
            if (answer[i].equals(answerChose)) {
                guess.setAnswerfinal(answerChose);
            }
        }
        if(guess.getAnswerfinal()==null||guess.getAnswerfinal().equals("")){
            return false;
        }

        List<GuessUser> guessUserList = WorkBot.guessUserMapper.selectByGuessId(guessId);
        List<GuessUser> guessUserWinList = new ArrayList<>();
       // System.out.println(guessUserList.size());
        double tokenTotalFinal = guess.getTokentotal();
        int tokenTimes = 0;
        int winTimes = 0;
        List<Integer> userCount = new ArrayList<>();
        for (int i = 0; i < guessUserList.size(); i++) {
            System.out.println("here");
            tokenTotalFinal += guessUserList.get(i).getGuesstoken();
            tokenTimes += guessUserList.get(i).getGuesstimes();
            if(guessUserList.get(i).getAnswer().equals(answerChose)){
                guessUserWinList.add(guessUserList.get(i));
                winTimes += guessUserList.get(i).getGuesstimes();
            }
            if(!userCount.contains(guessUserList.get(i).getTelegramid())){
                userCount.add(guessUserList.get(i).getTelegramid());
            }
        }

        //每注赢多少
        double tokenTimesWin = tokenTotalFinal/winTimes;
        List<Integer> winCount = new ArrayList<>();
        for(int i = 0; i<guessUserWinList.size();i++){
            List<Users> usersList= WorkBot.usersMapper.selectByTelegramId(guessUserWinList.get(i).getTelegramid());
            if(usersList!=null&&usersList.size()==1){
                Users users = usersList.get(0);
                users.setCandynum(users.getCandynum()+guessUserWinList.get(i).getGuesstimes()*tokenTimesWin);
                WorkBot.usersMapper.updateByPrimaryKey(users);
            }else{
                TelegramUser telegramUser = WorkBot.telegramUserMapper.selectByPrimaryKey(guessUserWinList.get(i).getTelegramid());
                    telegramUser.setToken(telegramUser.getToken()+guessUserWinList.get(i).getGuesstimes()*tokenTimesWin);
                    WorkBot.telegramUserMapper.updateByPrimaryKey(telegramUser);
            }
            guessUserWinList.get(i).setReward(guessUserWinList.get(i).getGuesstimes()*tokenTimesWin);
            WorkBot.guessUserMapper.updateByPrimaryKey(guessUserWinList.get(i));
            if(!winCount.contains(guessUserWinList.get(i).getTelegramid())){
                winCount.add(guessUserWinList.get(i).getTelegramid());
            }
        }
        guess.setTokentotalfinally(tokenTotalFinal);
        guess.setTokentimestotal(tokenTimes);
        guess.setWincount(winCount.size());
        guess.setJoincount(userCount.size());

        WorkBot.guessMapper.updateByPrimaryKey(guess);

        //sendMsg
        SendPhoto sendPhoto = new SendPhoto();
        sendPhoto.setNewPhoto(photo);
        String msg = guess.getQuestion()+"\n"+"\n"+"-------------"+"\n";
        msg+= "本次竞猜正确选项是"+guess.getAnswerfinal()+"\n";
        msg+= "本次竞猜单注投注金额为"+guess.getTokentimes()+WorkBot.bitName+",官方注入"+guess.getTokentotal()+"\n";
        msg+= "总奖金为"+guess.getTokentotalfinally()+"\n";
        msg+= "共有"+guess.getJoincount()+"人参与竞猜,"+"总投注"+guess.getTokentimestotal()+"\n";
        msg+= "有"+guess.getWincount()+"人猜中,总获奖注数"+winTimes+"\n";
        msg+= "查询命令: "+"/guess_"+guessId;
        sendPhoto.setCaption(msg);
        sendPhoto.setChatId(chatId);
        try {
            this.sendPhoto(sendPhoto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    //处理用户投注
    public boolean hasGuessing() {
        int id = update.getCallbackQuery().getFrom().getId();
        String callback = update.getCallbackQuery().getData();
        String callbackList[] = callback.split("\\*\\*");
        boolean isUsers = false;
        boolean isTelegram = false;
        double hasToken = 0;
        TelegramUser telegramUser = new TelegramUser();
        List<Users> usersList = new ArrayList<>();
        Users users = new Users();
        //在投注这一期
        if (BotMethodSwitch.guessId.contains(Integer.parseInt(callbackList[0]))) {
            //查看是否有此用户
            usersList = WorkBot.usersMapper.selectByTelegramId(id);
            if (usersList != null && usersList.size() == 1) {
                isUsers = true;
                users = usersList.get(0);
                hasToken = users.getCandynum();
            } else {
                telegramUser = WorkBot.telegramUserMapper.selectByPrimaryKey(id);
                if (telegramUser != null) {
                    isTelegram = true;
                    hasToken = telegramUser.getToken();
                }
            }
            //若有此用户
            if (isUsers || isTelegram) {
                int guessTimes = 0;
                double guessToken = 0;
                double nowToken = 0;
                GuessUser guessUser = new GuessUser();
                guessUser.setGuessid(Integer.parseInt(callbackList[0]));
                guessUser.setAnswer(callbackList[1]);
                guessUser.setTelegramid(id);
                guessUser.setGettime(new Date());

                Guess guess = WorkBot.guessMapper.selectByPrimaryKey(Integer.parseInt(callbackList[0]));
                //区分投注多少
                if (callbackList[2].equals("1")) {           //一注
                    if (hasToken >= guess.getTokentimes()) {
                        guessTimes = 1;
                        guessToken = guess.getTokentimes();
                    }
                } else if (callbackList[2].equals("2")) {      //十注
                    if (hasToken >= guess.getTokentimes() * 10) {
                        guessTimes = 10;
                        guessToken = guess.getTokentimes() * 10;
                    }
                } else if (callbackList[2].equals("3")) {      //梭哈
                    if (hasToken >= guess.getTokentimes()) {
                        guessTimes = new Double(hasToken / guess.getTokentimes()).intValue();
                        guessToken = guessTimes * guess.getTokentimes();
                    }
                }
                //判断是否够钱投了注
                if (guessTimes != 0) {
                    nowToken = hasToken - guessToken;
                    guessUser.setGuesstimes(guessTimes);
                    guessUser.setGuesstoken(guessToken);
                    WorkBot.guessUserMapper.insert(guessUser);
                    if (isUsers) {
                        users.setCandynum(nowToken);
                        WorkBot.usersMapper.updateByPrimaryKey(users);
                        this.sendMessage(chatId, update.getCallbackQuery().getFrom().getFirstName() + "您好，您成功投了" + guessTimes + "注," + "您还剩" + nowToken + "个" + WorkBot.bitName);
                    } else if (isTelegram) {
                        telegramUser.setToken(nowToken);
                        WorkBot.telegramUserMapper.updateByPrimaryKey(telegramUser);
                        this.sendMessage(chatId, update.getCallbackQuery().getFrom().getFirstName() + "您好，您成功投了" +
                                guessTimes + "注," + "您还剩" + nowToken + "个" + WorkBot.bitName + "绑定糖果助手可得更多积分");
                    }
                } else {
                    this.sendMessage(chatId, update.getCallbackQuery().getFrom().getFirstName() + "您好，您的token不足，您目前拥有" + hasToken + "个" + WorkBot.bitName);
                }
            } else {
                TelegramUser telegramUser1 = new TelegramUser();
                telegramUser1.setToken(0.0);
                telegramUser1.setTelegramid(update.getCallbackQuery().getFrom().getId());
                WorkBot.telegramUserMapper.insert(telegramUser1);
                this.sendMessage(chatId, update.getCallbackQuery().getFrom().getFirstName() + "您好，您的token不足，您目前拥有" + 0 + "个" + WorkBot.bitName);
            }
            //操作
            //创建telegram,您还未获得任何token，您可以。。
        }
        //不在此期
        else {
            this.sendMessage(chatId, update.getCallbackQuery().getFrom().getFirstName()+"您好，此竞猜已结束,发送/guess_" + callbackList[0] + " ,即可查看自己投注情况");
        }
        return true;
    }

    //guess


    public void sendMessage(long chatId, String text) {
        SendMessage message = new SendMessage() // Create a SendMessage object with mandatory fields
                .setChatId(chatId)
                .setText(text);
        try {
            execute(message); // Call method to send the message
        } catch (TelegramApiException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getBotUsername() {
        return "ShineChainTestKeyBoard_bot";
    }

    @Override
    public String getBotToken() {
        return "659884345:AAGDnH82Ccc79w5CM-vC27D67cmM8610IOs";
    }

    public InviteCheckBot(DefaultBotOptions options) {
        super(options);
    }
}

